package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.util.EmployeeQueryObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Transactional
    @Override
    public void insert(Employee emp, Long[] ids) {
        //加密密码
        //密码加密,使用用户名作为加密的“盐”
        emp.setPassword(new Md5Hash(emp.getPassword(),emp.getName()).toString());
        employeeMapper.insert(emp);
        //  如果有选择角色则设置中间表
        if (ids != null && ids.length > 0) {
            /*for (Long roleId : ids) {
                employeeMapper.insertRelation(emp.getId(),roleId);
            }*/
            //  批量保存关系的方法
            employeeMapper.insertAllRelation(emp.getId(),ids);
        }
    }

    @Transactional
    @Override
    public void deleteById(Long id) {
        // 先删除员工的跟角色的关系(删除中间表关系)
        employeeMapper.deleteRelation(id);
        employeeMapper.deleteByPrimaryKey(id);
    }
    @Transactional
    @Override
    public void update(Employee emp, Long[] ids) {
        employeeMapper.updateByPrimaryKey(emp);
        //  如果有选择角色则设置中间表
        employeeMapper.deleteRelation(emp.getId());// 先删除原来的关系
        if(ids!=null&&ids.length>0){
            /*for (Long roleId : ids) {
                //employeeMapper.insertRelation(emp.getId(),roleId);

            }*/
            //  批量保存关系的方法
            employeeMapper.insertAllRelation(emp.getId(),ids);
        }
    }

    @Override
    public Employee selectById(Long id) {

        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> listAll() {
        return employeeMapper.selectAll();
    }

    @Override
    public PageInfo<Employee> query(EmployeeQueryObject qo) {
       /* int count = employeeMapper.queryForCount(qo);
        if (count == 0) {
            return new PageResult<>(qo.getPageSize(), qo.getCurrentPage(), count, Collections.emptyList());
        }*/
        // 使用分页插件,传入当前页,每页显示数量
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<Employee> employees = employeeMapper.queryForList(qo);
        return new PageInfo<Employee>(employees);
    }
    // 批量删除
    @Override
    public void batchDelete(Long[] ids) {
        employeeMapper.batchDelete(ids);
    }

    @Override
    public Employee selectByName(String name) {
        return employeeMapper.selectByName(name);
    }

    @Override
    public Workbook exportXls() {
        //创建excel文件
        Workbook wb = new HSSFWorkbook();
        //创建sheet页
        Sheet sheet = wb.createSheet("员工列表");
        //在sheet页上的第一行作为标题行
        Row row = sheet.createRow(0);
        //设置标题行内容到单元格中
        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("邮箱");
        row.createCell(2).setCellValue("年龄");
        //查询员工数据
        List<Employee> employees = employeeMapper.selectAll();
        //遍历员工数据一个员工一行循环写出
        for (int i = 0; i < employees.size(); i++) {
            Employee employee = employees.get(i);
            //创建行(因为第一行写了标题,这里从第二行开始)
            row = sheet.createRow(i+1);
            //设置员工数据内容到单元格中
            row.createCell(0).setCellValue(employee.getName());
            row.createCell(1).setCellValue(employee.getEmail());
            row.createCell(2).setCellValue(employee.getAge());
        }
        return wb;
    }

    public void importXls(MultipartFile file) throws Exception {
        //以excel的方式去读取上传的文件
        Workbook wb = new HSSFWorkbook(file.getInputStream());
        //读取第一页
        Sheet sheet = wb.getSheetAt(0);
        //获取最后一行的索引
        int lastRowNum = sheet.getLastRowNum();
        //忽略标题行开始读
        for (int i = 1; i <= lastRowNum; i++) {
            //获取行内容
            Row row = sheet.getRow(i);
            //用户名
            String name = row.getCell(0).getStringCellValue();
            //如果用户名是空,就跳过当前循环(换下一行)
            if(!StringUtils.hasLength(name.trim())){
                continue;
            }
            //创建员工对象封装每一行的数据
            Employee employee = new Employee();
            //封装姓名
            employee.setName(name);
            //封装邮箱
            employee.setEmail(row.getCell(1).getStringCellValue());
            //获取年龄单元格(第三个)
            Cell ageCell = row.getCell(2);
            //判断年龄单元格是什么类型选择用什么格式读年龄,并封装
            if (ageCell.getCellType().equals(CellType.STRING)) {//文本类型
                //文本格式(转成Integer)
                employee.setAge(Integer.valueOf(ageCell.getStringCellValue()));
            }else {
                //数值类型(获取到是double的,强转成int)
                employee.setAge((int)ageCell.getNumericCellValue());
            }
            //设置默认密码1
            employee.setPassword("1");
            //调用员工保存
            this.insert(employee,null);
        }
    }

    @Override
    public List<Employee> selectByRoleSn(String market, String market_manager) {
        return employeeMapper.selectByRoleSn(market, market_manager);
    }
}
